package com.voicechat.firstmet.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tencent.av.sdk.AVEndpoint;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.MsgGifGridViewAdapter;
import com.voicechat.firstmet.adapter.ViewPagerAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CharmBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.VoiceChatBean;
import com.voicechat.firstmet.bean.VoiceChatIngWSBean;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.client.RequestSendGiftBean;
import com.voicechat.firstmet.client.RequestVoiceChatBean;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.imcontrol.IRoomView;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.imcontrol.RoomHelper;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.net.service.PersonDataService;
import com.voicechat.firstmet.realm.ListBean;
import com.voicechat.firstmet.service.FloatVideoWindowService;
import com.voicechat.firstmet.utils.ContDownUtil;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.LinearGradientFontSpan;
import com.voicechat.firstmet.utils.NetworkConnectChangedReceiver;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.RealmUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.ScreenUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.AutoVerticalScrollTextView;
import com.voicechat.firstmet.view.CircleImageView;
import com.voicechat.firstmet.view.CirclePageIndicator;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: InviteVoiceChatActivity
 * @Description: 等待接听和接听成功页面
 * @Author: ljp
 * @CreateDate: 2018/11/12 14:52
 * @Version: 1.0
 */
public class InviteVoiceChatActivity extends BaseActivity implements IRoomView {
    @BindView(R.id.image_icon_backgroud)
    ImageView imageIconBackgroud;
    @BindView(R.id.image_icon)
    CircleImageView imageIcon;
    @BindView(R.id.image_icon_other)
    CircleImageView imageIconOther;
    @BindView(R.id.image_isanchor)
    ImageView imageIsanchor;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.image_sex)
    ImageView imageSex;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.linear_sex_age)
    LinearLayout linearSexAge;
    @BindView(R.id.image_vip)
    ImageView imageVip;
    @BindView(R.id.tv_voice_state)
    TextView tvVoiceState;
    @BindView(R.id.image_close)
    ImageView imageClose;
    @BindView(R.id.image_answer)
    ImageView imageAnswer;
    @BindView(R.id.linear_voice_chat_state_invite)
    LinearLayout linearVoiceChatStateInvite;
    @BindView(R.id.image_hang_up)
    ImageView imageHangUp;
    @BindView(R.id.linear_voice_chat_state_wait)
    LinearLayout linearVoiceChatStateWait;
    @BindView(R.id.tv_voice_pay_way)
    TextView tvVoicePayWay;
    @BindView(R.id.tv_gold)
    TextView tvGold;
    @BindView(R.id.rela_wait_answer)
    RelativeLayout relaWaitAnswer;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.tv_nike_name)
    TextView tvNikeName;
    @BindView(R.id.image_more)
    ImageView imageMore;
    @BindView(R.id.auto_gif_notice)
    AutoVerticalScrollTextView autoGifNotice;
    @BindView(R.id.linear_notice)
    LinearLayout linearNotice;
    @BindView(R.id.image_sca)
    ImageView imageSca;
    @BindView(R.id.image_mic)
    ImageView imageMic;
    @BindView(R.id.image_gif)
    ImageView imageGif;
    @BindView(R.id.rela_answer_success)
    RelativeLayout relaAnswerSuccess;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.svgImage)
    SVGAImageView svgImage;
    @BindView(R.id.image_is_anchor)
    ImageView imageIsAnchor;

    private String type;//判断是接听还是拨打电话  0接听  1拨打
    private String TAG = "InviteVoiceChatActivity";
    // private VoiceChatBean voiceChat;
    //private VoiceChatBean.MapBean.CalledUserBean calledUser;
    private static VoiceChatBean.MapBean.CalledUserBean calledUserBean;//语音接收者信息
    private static VoiceChatBean.MapBean.CallingUserBean callingUserBean;//语音发送者信息
    private VoiceChatIngWSBean.ObjectBean object;
    private RoomHelper helper;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String flag;//0 等待接听页面  1 接听成功页面
    private int roomId;
    private String token;
    private String deviceInfo;
    private boolean selectedMic = true;
    private Runnable timeRunable;
    //计时器
    private Handler mhandle = new Handler();
    private Handler handle = new Handler();
    private boolean isPause = false;//是否暂停
    private static long currentSecond; //当前毫秒数
    private long currentSecondNow = 0;//当前毫秒数
    private int[] numbers;//数字图片
    private ContDownUtil contDownUtil;
    private boolean isAnswer = false;//是否未接通且未主动挂断
    private ServiceConnection mVideoServiceConnection;
    private PowerManager.WakeLock mWakeLock;
    private NetworkConnectChangedReceiver netWorkStateReceiver;
    private boolean isEnd = false;//是否结束
    private ArrayList<CoummunityNotice.PageBean.ListBean> coummunityNotices = new ArrayList<>();
    private Thread thread;
    private String voiceId;
    private boolean isFlag = false;
    private boolean isConner = false;//是否接通
    private int itCount = 0;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_invite_voice_chat;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager != null) {
            mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock");
        }
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        Bundle bundle = getIntent().getBundleExtra("bundle");
        calledUserBean = bundle.getParcelable("voiceChat");
        callingUserBean = bundle.getParcelable("voiceChatCalling");
        object = bundle.getParcelable("object");
        type = getIntent().getStringExtra("type");
        flag = getIntent().getStringExtra("flag");
        roomId = bundle.getInt("roomId");
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        helper = new RoomHelper(this);
        helper.setRootView();
        if (flag.equals("0")) {//0 等待接听页面  1 接听成功页面
            try {
                AssetFileDescriptor fd = getAssets().openFd("voice_prompt.mp3");
                MediaUtil.getInstance().play(fd.getFileDescriptor(),fd.getStartOffset(),fd.getLength());
            } catch (IOException e) {
                e.printStackTrace();
            }
            initView();
        } else if (flag.equals("1")) {
            if(MediaUtil.getInstance().getPlayer().isPlaying()){
                MediaUtil.getInstance().stop();
            }
            initSuccessView();
        }
        // initService();
        mVideoServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // 获取服务的操作对象
                FloatVideoWindowService.MyBinder binder = (FloatVideoWindowService.MyBinder) service;
                binder.getService();
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i(TAG, "onServiceDisconnected: ------name-------" + name.getClassName());
            }
        };
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //监听接听方是否接听了广播
        initService();
    }
    private void initService() {
        //监听接听方是否接听了广播
        BroadcastManager.getInstance(activity).addAction("2003", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Log.i(TAG, "onReceive: ----2003----");
                isAnswer = true;//已经接听
                if(MediaUtil.getInstance().getPlayer().isPlaying()){
                    MediaUtil.getInstance().stop();
                }
                initSuccessView();
            }
        });
        //监听是否余额不足
        BroadcastManager.getInstance(activity).addAction("2004", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(TAG, "onReceive: ----------2004---");
                VoiceChatIngWSBean.ObjectBean voiceChatIngWSBean = intent.getParcelableExtra("result");
                //Log.i(TAG, "onReceive: -----voiceChatIngWSBean----" + voiceChatIngWSBean.toString());
                if (voiceChatIngWSBean != null && !TextUtils.isEmpty(voiceChatIngWSBean.getVoiceId())) {
                    voiceId = voiceChatIngWSBean.getVoiceId();
                    if (voiceChatIngWSBean.getGold() < 0) {
                        isPause = true;
                        isEnd = true;
                        if (!isFlag ) {
                            isFlag = true;
                            judeEvaluate();
                        }
                    }
                }
            }
        });
        //对方挂断了
        BroadcastManager.getInstance(activity).addAction("2008", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
              // toast_MakeText("2008");
                itCount++;
                Log.i(TAG, "onReceive: ----2008----itCount--" + itCount);
                //finish();
                isPause = true;
                isEnd = true;
                if (isConner) {
                    if (!isFlag && itCount == 1) {
                        isFlag = true;
                        judeEvaluate();
                    }
                } else {
                    finish();
                }
            }
        });

        //自己送礼物失败 余额不足
        BroadcastManager.getInstance(activity).addAction("2006", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                VoiceChatIngWSBean.ObjectBean voiceChatIngWSBean = intent.getParcelableExtra("result");
                if (voiceChatIngWSBean.getSend() == 1) {
                    toast_MakeText(getResources().getString(R.string.send_gift));
                }
            }
        });
        //对方拒绝了
        BroadcastManager.getInstance(activity).addAction("2009", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //  Log.i(TAG, "onReceive: ----2009----");
                isPause = true;
                finish();
            }
        });
        //对方网络异常
        BroadcastManager.getInstance(activity).addAction("2010", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //    Log.i(TAG, "onReceive: ----2010----");
                //toast_MakeText("2010");
                isPause = true;
                isEnd = true;
                finish();
            }
        });
        //自己掉线
        BroadcastManager.getInstance(activity).addAction("2011", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //   Log.i(TAG, "onReceive: ----2011----");
                isPause = true;
                finish();
            }
        });
        //无网络监听
        BroadcastManager.getInstance(activity).addAction("finish", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //   Log.i(TAG, "onReceive: ----finish----");
                //if(type.equals("0")) {//判断是接听还是拨打电话  0接听  1拨打
                finish();
                //}
            }
        });
        //收到礼物
        BroadcastManager.getInstance(activity).addAction("2007", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                VoiceChatIngWSBean.ObjectBean voiceChatIngWSBean = intent.getParcelableExtra("result");
                //有动画播放动画
                if (!TextUtils.isEmpty(voiceChatIngWSBean.getAnimationUrl())) {
                    try {
                        if (svgImage.getVisibility() == View.VISIBLE) {
                            svgImage.setVisibility(View.GONE);
                        }
                        loadAnimation(new URL(OssConfig.OSS_HTTP + voiceChatIngWSBean.getAnimationUrl()));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                } else {//没有动画显示送出礼物数量popu
                    if (PopUtils.isPopShowing()) {
                        PopUtils.hidePopupWindow();
                    }
                    showGiftPopu(voiceChatIngWSBean.getGiftName(), voiceChatIngWSBean.getGiftNumber(), voiceChatIngWSBean.getImgUrl());
                }
            }
        });
    }

    private long sendTime = 0L;

    public static InviteVoiceChatActivity newInstance() {
        InviteVoiceChatActivity fragment = new InviteVoiceChatActivity();
        return fragment;
    }

    /**
     * @return
     * @method
     * @description 接听成功数据控件实例化
     * @date: 2018/11/21 21:09
     * @author: ljp
     */
    private void initSuccessView() {
        isConner = true;//已经接听
        imageMic.setSelected(selectedMic);
        relaAnswerSuccess.setVisibility(View.VISIBLE);
        relaWaitAnswer.setVisibility(View.GONE);
        if (type.equals("0")) {
            GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + object.getAvatarUrl(), imageIconOther);
            tvNikeName.setText(object.getNickName());
            if (object.getType() == 2) {////1普通用户2主播
                imageIsAnchor.setVisibility(View.VISIBLE);
            } else {
                imageIsAnchor.setVisibility(View.GONE);
            }
        } else {
            GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + calledUserBean.getAvatarUrl(), imageIconOther);
            tvNikeName.setText(calledUserBean.getNickName());
            if (calledUserBean.getType() == 2) {////1普通用户2主播
                imageIsAnchor.setVisibility(View.VISIBLE);
            } else {
                imageIsAnchor.setVisibility(View.GONE);
            }
        }
        timeRunable = new Runnable() {
            @Override
            public void run() {
                currentSecondNow = currentSecondNow + 1000;
                currentSecond = currentSecondNow;
                //Log.i(TAG, "run: --------"+currentSecond);
                tvTime.setText(Utils.getFormatHMS(currentSecondNow));
                //向服务发送广播，更新时间
                BroadcastManager.getInstance(App.getContext()).sendBroadcast("time", String.valueOf(currentSecondNow));
                if (!isPause) {
                    //递归调用本runable对象，实现每隔一秒一次执行任务
                    mhandle.postDelayed(this, 1000);
                }
            }
        };
        mhandle.postDelayed(timeRunable, 0);
        Runnable heartBeatRunnable = new Runnable() {
            @Override
            public void run() {
                if (System.currentTimeMillis() - sendTime >= WsManager.HEART_BEAT_RATE) {
                    //像服务器发送计费消息
                    if (type.equals("1") && !isEnd) {
                        try {
                            //用户给用户，用户给主播打电话，主播给主播打电话（主叫方扣钱）
                            RequestVoiceChatBean requestBean = new RequestVoiceChatBean(2004, new RequestVoiceChatBean.ObjectBean(calledUserBean.getId(), callingUserBean.getId()));
                            WsManager.getInstance(context).sendMessage(requestBean);
                            sendTime = System.currentTimeMillis();
                        } catch (NullPointerException e) {
                        }
                    }
                }
                if (handle != null) {
                    handle.postDelayed(this, WsManager.HEART_BEAT_RATE); //每隔一定的时间，对长连接进行一次心跳检测
                }
            }
        };
        handle.postDelayed(heartBeatRunnable, 0);
        initNoticeHttp();
    }

    /**
     * @return
     * @method
     * @description 公告
     * @date: 2018/12/13 10:53
     * @author: ljp
     */
    private void initNoticeHttp() {
        MeInfoService.queryVoiceNotice(token, deviceInfo).subscribe(coummunityNotice -> {
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                coummunityNotices.clear();
                coummunityNotices.addAll(coummunityNotice.getPage().getList());
                setScrollText(autoGifNotice);
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(coummunityNotice.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }

    /**
     * 公告
     */
    public void setScrollText(AutoVerticalScrollTextView newHomeNotice) {
        newHomeNotice.setText(coummunityNotices.get(0).getContent());
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 199)
                    if (coummunityNotices.size() != 0) {
                        newHomeNotice.next();
                        number++;
                        newHomeNotice.setText(coummunityNotices.get(number % coummunityNotices.size()).getContent());
                    }
            }
        };
        thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    SystemClock.sleep(5000);
                    handler.sendEmptyMessage(199);
                }
            }
        };
        thread.start();
    }

    /**
     * @return
     * @method
     * @description 等待接听控件数据实例化
     * 判断是接听还是拨打电话  0接听  1拨打
     * @date: 2018/11/12 19:00
     * @author: ljp
     */
    private void initView() {
        relaWaitAnswer.setVisibility(View.VISIBLE);
        relaAnswerSuccess.setVisibility(View.GONE);
        if (type.equals("0")) {//判断是接听还是拨打电话  0接听  1拨打
            linearVoiceChatStateInvite.setVisibility(View.VISIBLE);
            linearVoiceChatStateWait.setVisibility(View.GONE);
            GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + object.getAvatarUrl(), imageIcon);
            GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + object.getAvatarUrl(), imageIconBackgroud);
            if (object.getVType() == 0) {// 会员等级 0非会员 1月会员 2年会员
                imageVip.setVisibility(View.GONE);
            } else if (object.getVType() == 1) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_month);
            } else if (object.getVType() == 2) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_year);
            }
            if (!TextUtils.isEmpty(object.getBirthday())) {
                tvAge.setText(Utils.getAge(object.getBirthday()));
            }
            if (object.getGender() == 1) {//性别  1男2女
                linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
                imageSex.setImageResource(R.mipmap.boy);
            } else {
                linearSexAge.setBackgroundResource(R.mipmap.sex_red);
                imageSex.setImageResource(R.mipmap.girl);
            }
            Log.i(TAG, "initView: -----------"+object.toString());
            //判断对方是否是主播
            if (object.getType() == 2) {////1普通用户2主播  0接听
                imageIsanchor.setVisibility(View.VISIBLE);
                if (mySeleInfo.getType() == 1) {//自己是用户
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_you));
                    tvGold.setText(object.getGold() + "金币/分钟");
                } else {
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_other));
                    tvGold.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                }
            } else {
                imageIsanchor.setVisibility(View.GONE);
                if (mySeleInfo.getType() == 1) {//如果对方是用户，自己是主播
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_other));
                    tvGold.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                } else {
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_other));
                    tvGold.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                }
            }
            tvVoiceState.setText(getResources().getText(R.string.voice_state_invite));
            //tvGold.setText(object.getGold() + "金币/分钟");
            name.setText(object.getNickName());
        } else {
            helper.createRoom(roomId);
            linearVoiceChatStateInvite.setVisibility(View.GONE);
            linearVoiceChatStateWait.setVisibility(View.VISIBLE);
            GlideLoadUtils.getInstance().glideLoad(activity, OssConfig.OSS_HTTP + calledUserBean.getAvatarUrl(), imageIcon);
            GlideLoadUtils.getInstance().glideLoad(activity, OssConfig.OSS_HTTP + calledUserBean.getAvatarUrl(), imageIconBackgroud);
            if (calledUserBean.getVType() == 0) {// 会员等级 0非会员 1月会员 2年会员
                imageVip.setVisibility(View.GONE);
            } else if (calledUserBean.getVType() == 1) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_month);
            } else if (calledUserBean.getVType() == 2) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_year);
            }
            if (!TextUtils.isEmpty(calledUserBean.getBirthday())) {
                tvAge.setText(Utils.getAge(calledUserBean.getBirthday()));
            }
            if (calledUserBean.getGender() == 1) {//性别  1男2女
                linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
                imageSex.setImageResource(R.mipmap.boy);
            } else {
                linearSexAge.setBackgroundResource(R.mipmap.sex_red);
                imageSex.setImageResource(R.mipmap.girl);
            }
            //判断对方是否是主播  1
            if (calledUserBean.getType() == 2) {////1普通用户2主播     1拨打
                imageIsanchor.setVisibility(View.VISIBLE);
                if (mySeleInfo.getType() == 1) {//如果接听方是主播，自己是用户
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_you));
                    tvGold.setText(calledUserBean.getGold() + "金币/分钟");
                } else {
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_you));
                    tvGold.setText(calledUserBean.getGold() + "金币/分钟");
                }
            } else {
                imageIsanchor.setVisibility(View.GONE);
                if (mySeleInfo.getType() == 1) {//如果对方是用户，自己是主播
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_you));
                    tvGold.setText(calledUserBean.getGold() + "金币/分钟");
                } else {
                    tvVoicePayWay.setText(getResources().getText(R.string.voice_pay_way_other));
                    tvGold.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                }
            }
            tvVoiceState.setText(getResources().getText(R.string.voice_state_wait));
            name.setText(calledUserBean.getNickName());
            contDownUtil = new ContDownUtil(60, activity);
            contDownUtil.myStart();
            contDownUtil.setGetTimeFinish(new ContDownUtil.GetTimeFinish() {
                //完成时回调
                @Override
                public void downFinish() {
                    if (!isAnswer) {
                        Log.i(TAG, "downFinish: ------------");
                        calldrefuseAnswer("0", "0", "0");
                        MediaUtil.getInstance().stop();
                        finish();
                    }
                }
                //倒计时回调
                @Override
                public void onTick(long millisUntilFinished) {
                    //Log.i(TAG, "onTick: ---millisUntilFinished-----"+millisUntilFinished);
                    if (isAnswer) {
                        contDownUtil.onFinish();
                    }
                }
            });
        }
    }

    public static long getCurrentSecond() {
        return currentSecond;
    }

    @OnClick({R.id.image_close, R.id.image_answer, R.id.image_hang_up, R.id.iv_close,
            R.id.image_sca, R.id.image_mic, R.id.image_gif,R.id.image_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_close://拒绝
                refuseAnswer("1", "0", "0");
                break;
            case R.id.image_answer://接听
                //判断是否开启了麦克风权限
                if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.RECORD_AUDIO}, 1);
                } else {
                    helper.joinRoom(object.getRoomId());
                }
                break;
            case R.id.image_hang_up://挂断
                isAnswer = true;
                calldrefuseAnswer("0", "0", "0");
                break;
            case R.id.iv_close://聊天挂断
                //判断是接听还是拨打电话  0接听  1拨打
                //先弹出询问框
                /*if (type.equals("0")) {
                    refuseAnswer("1", "1");
                } else {
                    isEnd = true;
                    isPause = true;
                    calldrefuseAnswer("0", "1");
                }*/
                showCacheDialog();
                break;
            case R.id.image_sca://屏幕缩放
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Settings.canDrawOverlays(this)) {
                        startVideoService();
                    } else {
                        requestAlertWindowPermission();
                    }
                } else {
                    startVideoService();
                }
                break;
            case R.id.image_mic://开关麦克风
                if (selectedMic) {
                    imageMic.setSelected(false);
                    helper.enableMic(false);
                    selectedMic = false;
                } else {
                    imageMic.setSelected(true);
                    helper.enableMic(true);
                    selectedMic = true;
                }
                break;
            case R.id.image_gif://赠送礼物
                //判断是接听还是拨打电话  0接听  1拨打
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
                if (type.equals("0")) {
                    setPopuGift(object.getCalledId(), object.getCallingId());
                } else {
                    setPopuGift(callingUserBean.getId(), calledUserBean.getId());
                }
                break;
            case R.id.image_more:
                showPopu(view);
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 更多popu
     * @date: 2018/9/11 19:50
     * @author: ljp
     */
    private void showPopu(View view) {
        View inflate = View.inflate(this, R.layout.popu_window_function, null);
        TextView tvTimeMoney = inflate.findViewById(R.id.tv_time_money);
        TextView tvMoneyYue = inflate.findViewById(R.id.tv_money_yue);
        TextView tvAttention = inflate.findViewById(R.id.tv_attention);
        initHttpGetGold(mySeleInfo.getId(),tvMoneyYue,"金币");
        int viewY = (view.getBottom()  + (view.getHeight()));
        int viewX = view.getLeft() - (int) getResources().getDimension(R.dimen.x300);
        // 设置好参数之后再show
        int local[] = new int[2];
        //弹出控件的位置，坐标存在local数组
        view.getLocationOnScreen(local);
        int width = view.getWidth();
        int height = view.getHeight();
        int x = local[0] - (ScreenUtils.getScreenWidth(context) / 2) - width * 2;
        int y = local[1] - height;
        // 获得位置
        int popupWidth = inflate.getMeasuredWidth();
        int popupHeight = inflate.getMeasuredHeight();
        int i = (view.getLeft() - view.getWidth()) - (local[1] - popupHeight) * 2;
        /*PopUtils.showPopupWindow(view, inflate, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, i, 0, true);*/
        PopUtils.showPopupWindow(inflate, view, activity, true, Gravity.NO_GRAVITY,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                -(int) getResources().getDimension(R.dimen.x280), 0, 1.0f);
        if(type.equals("0")){
            //判断对方是否是主播
            if (object.getType() == 2) {////1普通用户2主播  0接听
                if (mySeleInfo.getType() == 1) {//自己是用户
                    tvTimeMoney.setText(object.getGold() + "金币/分钟");
                } else {
                    tvTimeMoney.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                }
            } else {
                if (mySeleInfo.getType() == 1) {//如果对方是用户，自己是主播
                    tvTimeMoney.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                } else {
                    tvTimeMoney.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                }
            }
            setHomeState(tvAttention,object.getCallingId());
        }else {
            //判断对方是否是主播  1
            if (calledUserBean.getType() == 2) {////1普通用户2主播     1拨打
                if (mySeleInfo.getType() == 1) {//如果接听方是主播，自己是用户
                    tvTimeMoney.setText(calledUserBean.getGold() + "金币/分钟");
                } else {
                    tvTimeMoney.setText(calledUserBean.getGold() + "金币/分钟");
                }
            } else {
                if (mySeleInfo.getType() == 1) {//如果对方是用户，自己是主播
                    tvTimeMoney.setText(calledUserBean.getGold() + "金币/分钟");
                } else {
                    tvTimeMoney.setText(mySeleInfo.getGold() / 10 + "金币/分钟");
                }
            }
            setHomeState(tvAttention,calledUserBean.getId());
        }
    }
    /**
     * @return
     * @method
     * @description 请求关注状态
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void setHomeState(TextView textView,String anchorId) {
        PersonDataService.showPersonState(token, deviceInfo, mySeleInfo.getId(), anchorId).subscribe(charmBean -> {
            //Log.i(TAG, "setHomeState: -----"+charmBean.getObject().toString());
            if (charmBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                CharmBean.ObjectBean object = charmBean.getObject();
                if (object.getState() == 1) {//1 未关注 2已经关注 3互相关注
                    textView.setText("关注");
                } else if (object.getState() == 2) {
                    textView.setText("已关注");
                } else if (object.getState() == 3) {
                    textView.setText("互相关注");
                }
            } else if (charmBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(charmBean.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }
    /**
     * @return
     * @method
     * @description 是否退出语音通话
     * @date: 2018/11/1 19:37
     * @author: ljp
     */
    private void showCacheDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        //normalDialog.setTitle("我是一个普通Dialog");
        normalDialog.setMessage("确认退出语音通话?");
        //normalDialog.setView(view);
       /* tvCacel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tvCacel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalDialog.dismiss();
            }
        });*/
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do  flag 1 接听挂断  2未接听挂断
                        if (type.equals("0")) {
                            refuseAnswer("1", "1", "1");
                        } else {
                            isEnd = true;
                            isPause = true;
                            calldrefuseAnswer("0", "1", "1");
                        }
                        dialog.dismiss();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * @method
     * @description 弹出打赏页面
     * @date: 2018/11/19 19:51
     * @author: ljp
     * @return
     */
    ViewPager viewPagerGif;
    TextView tvGoldSum;
    LinearLayout linearRecharge;
    TextView tvSendGift;
    ImageView imageCloseCha;
    CirclePageIndicator llPointGroup;
    public static int gridColumn = 4;//grid的列数
    public static int gridNum = 8;//grid的一页总数
    private ViewPagerAdapter mAdapter;
    private List<GridView> gridViews;
    ListBean giftBean;//选中的礼物
    private int number;

    private void setPopuGift(String userId, String otherId) {
        View view = View.inflate(context, R.layout.popu_gift_fragment, null);
        tvSendGift = view.findViewById(R.id.tv_send);
        linearRecharge = view.findViewById(R.id.linear_recharge);
        tvGoldSum = view.findViewById(R.id.tv_gold_sum);
        viewPagerGif = view.findViewById(R.id.view_pager_gif);
        llPointGroup = view.findViewById(R.id.ll_point_group);
        imageCloseCha = view.findViewById(R.id.image_close);
        initPopuView();
        initDatas();
        initHttpGetGold(userId, tvGoldSum,"");
        PopUtils.initPopupWindow(activity, view, false);
        PopUtils.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = activity.getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                activity.getWindow().setAttributes(params);
                //giftBean = null;
            }
        });
        imageCloseCha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
            }
        });
        tvSendGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (giftBean != null) {
                    RequestSendGiftBean requestSendGiftBean;
                    if (type.equals("0")) {//判断是接听还是拨打电话  0接听  1拨打
                        requestSendGiftBean = new RequestSendGiftBean(RequestSendGiftBean.CODE, new RequestSendGiftBean.ObjectBean(object.getCalledId(), object.getCallingId(), giftBean.getId(), "1", 1));
                    } else {
                        requestSendGiftBean = new RequestSendGiftBean(RequestSendGiftBean.CODE, new RequestSendGiftBean.ObjectBean(calledUserBean.getId(), callingUserBean.getId(), giftBean.getId(), "1", 0));
                    }
                    WsManager.getInstance(context).sendMessageGift(requestSendGiftBean, giftBean.getName());
                    PopUtils.hidePopupWindow();
                    //有动画播放动画
                    if (!TextUtils.isEmpty(giftBean.getAnimationUrl())) {
                        try {
                            loadAnimation(new URL(OssConfig.OSS_HTTP + giftBean.getAnimationUrl()));
                            svgImage.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                    } else {//没有动画显示送出礼物数量popu
                        showGiftPopu(giftBean.getName(), number, giftBean.getImgUrl());
                    }
                    giftBean = null;
                } else {
                    toast_MakeText("请选择礼物");
                }
            }
        });
    }

    /**
     * @return
     * @method
     * @description 送礼物弹出数量
     * @date: 2018/11/22 18:40
     * @author: ljp
     */
    private void showGiftPopu(String name, int number, String url) {
        View view1 = View.inflate(context, R.layout.popu_voicechat_send_gift, null);
        PopUtils.showPopupWindow(imageGif, view1, activity);
        TextView tvGiftNum = view1.findViewById(R.id.tv_number);
        TextView tvGiftName = view1.findViewById(R.id.tv_gift_name);
        ImageView imageIconGift = view1.findViewById(R.id.image_gift_icon);
        tvGiftNum.setText(LinearGradientFontSpan.getRadiusGradientSpan("1", 0XFFFF77B9, 0xFFFD8989));
        tvGiftName.setText(name);
        GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + url, imageIconGift);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                PopUtils.hidePopupWindow();
            }
        }, 8000);
    }

    private void loadAnimation(URL url) {
        SVGAParser parser = new SVGAParser(this);
        resetDownloader(parser);
        parser.parse(url, new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                SVGADrawable drawable = new SVGADrawable(videoItem, requestDynamicItemWithSpannableText());
                svgImage.setVisibility(View.VISIBLE);
                svgImage.setImageDrawable(drawable);
                svgImage.setLoops(1);
                svgImage.startAnimation();
            }

            @Override
            public void onError() {
            }
        });
        svgImage.setCallback(new SVGACallback() {
            @Override
            public void onPause() {
            }

            @Override
            public void onFinished() {
                svgImage.setVisibility(View.GONE);
            }

            @Override
            public void onRepeat() {
            }

            @Override
            public void onStep(int frame, double percentage) {
            }
        });
    }

    /**
     * 你可以设置富文本到 ImageKey 相关的元素上
     * 富文本是会自动换行的，不要设置过长的文本
     *
     * @return
     */
    private SVGADynamicEntity requestDynamicItemWithSpannableText() {
        SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("----");
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(28);
        dynamicEntity.setDynamicText(new StaticLayout(
                spannableStringBuilder,
                0,
                spannableStringBuilder.length(),
                textPaint,
                0,
                Layout.Alignment.ALIGN_CENTER,
                1.0f,
                0.0f,
                false
        ), "banner");
        dynamicEntity.setDynamicDrawer(new Function2<Canvas, Integer, Boolean>() {
            @Override
            public Boolean invoke(Canvas canvas, Integer frameIndex) {
                Paint aPaint = new Paint();
                aPaint.setColor(Color.WHITE);
                canvas.drawCircle(50, 54, frameIndex % 5, aPaint);
                return false;
            }
        }, "banner");
        return dynamicEntity;
    }

    /**
     * 设置下载器，这是一个可选的配置项。
     *
     * @param parser
     */
    private void resetDownloader(SVGAParser parser) {
        parser.setFileDownloader(new SVGAParser.FileDownloader() {
            @Override
            public void resume(final URL url, final Function1<? super InputStream, Unit> complete, final Function1<? super Exception, Unit> failure) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url(url).get().build();
                        try {
                            Response response = client.newCall(request).execute();
                            complete.invoke(response.body().byteStream());
                        } catch (IOException e) {
                            e.printStackTrace();
                            failure.invoke(e);
                        }
                    }
                }).start();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 余额请求
     * @date: 2018/11/7 14:39
     * @author: ljp
     */
    private void initHttpGetGold(String userId, TextView textView,String text) {
        MeInfoService.goldDiamond(userId, token, deviceInfo).subscribe(goldBean -> {
            //Log.i(TAG, "initHttp: -------"+goldBean.getObject().toString());
            if (goldBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                textView.setText(goldBean.getObject().getGold() +text);
            } else {
                toast_MakeText(goldBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "initHttp: -----" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2018/11/13 10:07
     * @author: ljp
     */
    List<ListBean> listBeans;

    private void initPopuView() {
        gridViews = new ArrayList<>();
        listBeans = new ArrayList<>();
        listBeans.addAll(RealmUtils.getInstance()
                .getRealm()
                .where(ListBean.class)
                .findAll());
        mAdapter = new ViewPagerAdapter();
        viewPagerGif.setAdapter(mAdapter);
        llPointGroup.setVisibility(View.VISIBLE);
        llPointGroup.setViewPager(viewPagerGif);
    }

    /**
     * @return
     * @method
     * @description 礼物数据实例化
     * @date: 2018/11/20 11:23
     * @author: ljp
     */
    private void initDatas() {
        //计算viewpager一共显示几页
        int pageSize = listBeans.size() % gridNum == 0
                ? listBeans.size() / gridNum
                : listBeans.size() / gridNum + 1;
        for (int i = 0; i < pageSize; i++) {
            GridView gridView = new GridView(activity);
            MsgGifGridViewAdapter adapter = new MsgGifGridViewAdapter(listBeans, i);
            gridView.setNumColumns(gridColumn);
            gridView.setHorizontalSpacing(5);
            gridView.setVerticalSpacing(10);
            gridView.setAdapter(adapter);
            int finalI = i;
            adapter.setItemClick(new MsgGifGridViewAdapter.ItemClick() {
                @Override
                public void setItemClick(int position) {
                }
            });
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    adapter.setCheckd(true, position);
                    adapter.notifyDataSetChanged();
                    giftBean = adapter.getItem(position);
                    //toast_MakeText(adapter.getItem(position)+"");
                }
            });
            gridViews.add(gridView);
        }
        mAdapter.add(gridViews);
    }

    /**
     * @return
     * @method
     * @description 接听方拒绝接听
     * @date: 2018/11/22 11:11
     * @author: ljp  flag 1 接听挂断  2未接听挂断
     */
    private void refuseAnswer(String sign, String tag, String flag) {
        MeInfoService.exitVoiceChat(object.getCalledId(), token, deviceInfo, object.getCallingId(), sign, tag).subscribe(result -> {
            Log.i(TAG, "refuseAnswer: ---------" + result);
            // if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
            if (flag.equals("1")) {
                judeEvaluate();
            } else {
                finish();
            }
            // }
        }, throwable -> {
            Log.i(TAG, "refuseAnswer: --------" + throwable);
            if (flag.equals("1")) {
                judeEvaluate();
            } else {
                finish();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 拨打方方拒绝接听
     * @date: 2018/11/22 11:11
     * @author: ljp   flag 1 接听挂断  2未接听挂断
     */
    private void calldrefuseAnswer(String sign, String tag, String flag) {
        MeInfoService.exitVoiceChat(calledUserBean.getId(), token, deviceInfo, callingUserBean.getId(), sign, tag).subscribe(result -> {
            Log.i(TAG, "calldrefuseAnswer: ---------" + result);
            //if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
            if (flag.equals("1")) {
                //Log.i(TAG, "calldrefuseAnswer: ---------"+calledUserBean.toString());
                judeEvaluate();
            } else {
                finish();
            }
            // }
        }, throwable -> {
            if (flag.equals("1")) {
                // Log.i(TAG, "calldrefuseAnswer: ---------"+calledUserBean.toString());
                judeEvaluate();
            } else {
                finish();
            }
            // Log.i(TAG, "refuseAnswer: --------" + throwable);
        });
    }

    /**
     * @return
     * @method
     * @description 进入房间成功，
     * @date: 2018/11/12 18:56
     * @author: ljp
     */
    @Override
    public void onEnterRoom() {
        Log.i(TAG, "onEnterRoom: ---进入房间成功----");
        //判断是以什么身份进入房间成功的， //判断是接听还是拨打电话  0接听  1拨打
        if (type.equals("0")) {
            MeInfoService.voiceAnswer(object.getCalledId(), SPUtils.getEditoString(SPUtils.SP_TOKEN),
                    PhoneUtils.getDeviceInfo(context), object.getCallingId(), "0").subscribe(result1 -> {
                Log.i(TAG, "onEnterRoom: ----------" + result1.toString());
                if (result1.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    if(MediaUtil.getInstance().getPlayer().isPlaying()){
                        MediaUtil.getInstance().stop();
                    }
                    initSuccessView();
                }
            }, throwable -> {
                Log.i(TAG, "onEnterRoom: ---------" + throwable.toString());
            });
        } else {
            MeInfoService.rommSuccess(calledUserBean.getId(), token = SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context), callingUserBean.getId(),
                    roomId + "").subscribe(result -> {
                Log.i(TAG, "onEnterRoom: --------------" + result.toString());
                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    Log.i(TAG, "onEnterRoom: ------" + result.toString());
                } else {
                    toast_MakeText(result.getMsg());
                }
            }, throwable -> {
                toast_MakeText(getResources().getString(R.string.net_error));
            });
        }
    }

    /**
     * @return
     * @method
     * @description 进入房间失败
     * @date: 2018/11/12 18:56
     * @author: ljp
     */
    @Override
    public void onEnterRoomFailed(String module, int errCode, String errMsg) {
        Log.i(TAG, "onEnterRoomFailed: ---errCode---" + errCode + "--errMsg--" + errMsg);
        //判断是以什么身份进入房间失败的， //判断是接听还是拨打电话  0接听  1拨打
        toast_MakeText("接听失败");
        if (type.equals("0")) {
            MeInfoService.voiceAnswer(object.getCalledId(), SPUtils.getEditoString(SPUtils.SP_TOKEN),
                    PhoneUtils.getDeviceInfo(context), object.getCallingId(), "1").subscribe(result1 -> {
                Log.i(TAG, "onEnterRoom: ----------" + result1.toString());
                if (result1.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    //initSuccessView();
                }
            }, throwable -> {
                Log.i(TAG, "onEnterRoom: ---------" + throwable.toString());
            });
        } else {
            finish();
        }
        finish();
    }

    /**
     * @return
     * @method
     * @description 退出房间成功
     * @date: 2018/11/12 18:56
     * @author: ljp
     */
    @Override
    public void onQuitRoomSuccess() {
        Log.i(TAG, "onQuitRoomSuccess: ------");
    }

    /**
     * @return
     * @method
     * @description 退出房间失败
     * @date: 2018/11/12 18:57
     * @author: ljp
     */
    @Override
    public void onQuitRoomFailed(String module, int errCode, String errMsg) {
        Log.i(TAG, "onQuitRoomFailed: ------" + errMsg);

    }

    // 房间断开
    @Override
    public void onRoomDisconnect(int errCode, String errMsg) {
        Log.i(TAG, "onRoomDisconnect: ---errCode--" + errCode + "--errMsg--" + errMsg);

    }

    @Override
    public void onEndpointsUpdateInfo(int eventid, String[] updateList) {
        AVEndpoint avEndpoint = new AVEndpoint();
        for (int i = 0; i < updateList.length; i++) {
        }
    }

    // 处理Activity事件
    public void onPause() {
        helper.onPause();
        if (mWakeLock != null) {
            mWakeLock.acquire();
        }
        unregisterReceiver(netWorkStateReceiver);
        Log.i(TAG, "onPause: -----------");
        super.onPause();

    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    // 处理Activity事件
    public void onResume() {
        super.onResume();
        // Log.i(TAG, "onResume: ----------");
        helper.onResume();
        if (mWakeLock != null) {
            mWakeLock.acquire();
        }
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetworkConnectChangedReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ------");
        currentSecond = 0L;
        helper.quitRoom();
        timeRunable = null;
        if (intentService != null) {
            try {
                stopService(intentService);
                unbindService(mVideoServiceConnection);
            }catch (Exception e){
            }
        }
        if(MediaUtil.getInstance().getPlayer().isPlaying()){
            MediaUtil.getInstance().stop();
        }
        if (contDownUtil != null) {
            contDownUtil.cancel();
        }
        if (PopUtils.isPopShowing()) {
            PopUtils.hidePopupWindow();
        }
        BroadcastManager.getInstance(context).destroy("2008");
        BroadcastManager.getInstance(context).destroy("2004");
    }
    /**
     * ⑨重写onRequestPermissionsResult方法
     * 获取动态权限请求的结果,再开启录制音频
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            helper.joinRoom(object.getRoomId());
        } else {
            Toast.makeText(this, "用户拒绝了权限", Toast.LENGTH_SHORT).show();
            refuseAnswer("1", "0", "0");
            finish();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    Intent intentService;

    public void startVideoService() {
        moveTaskToBack(true);//最小化Activity
        intentService = new Intent(this, FloatVideoWindowService.class);//开启服务显示悬浮框
        bindService(intentService, mVideoServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private static final int REQUEST_CODE = 1;

    private void requestAlertWindowPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
           /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    startVideoService();
                    Log.i("onActivityResult", "onActivityResult granted");
                }
            }*/
        }
    }

    @Override
    protected void onRestart() {
        if (intentService != null) {
            try {
                stopService(intentService);
                unbindService(mVideoServiceConnection);
            }catch (Exception e){
            }
        }
        FloatVideoWindowService.newInstance().removeView();
        if (Utils.isServiceRunning(this, "com.voicechat.firstmet.service.FloatVideoWindowService")) {
            unbindService(mVideoServiceConnection);//不显示悬浮框
            stopService(intentService);
        }
        Log.i(TAG, "onRestart: -----从悬浮窗进来后重新设置画布(判断是不是接通了---" + Utils.isServiceRunning(this, "com.voicechat.firstmet.service.FloatVideoWindowService"));
        super.onRestart();
    }
    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * @return
     * @method
     * @description 评价页面判断
     * @date: 2018/12/12 20:18
     * @author: ljp
     */
    private void judeEvaluate() {
        Log.i(TAG, "judeEvaluate: ------type-------" + type);
        Intent intent = new Intent(activity, CallEndActivity.class);
        if (type.equals("0")) {//判断是接听还是拨打电话  0接听
            //判断对方是否是主播
            if (object.getType() == 2) {////1普通用户2主播  0接听
                if (mySeleInfo.getType() == 1) {//自己是付费方，跳到付费页面
                    voiceEndData(intent);
                } else {
                    removeActivity();
                }
            } else {
                removeActivity();
            }
        } else {
            if (calledUserBean != null) {
                //判断对方是否是主播  1
                if (calledUserBean.getType() == 2) {////1普通用户2主播     1拨打
                    //自己是付费方，跳到付费页面
                    voiceEndData(intent);
                } else {
                    if (mySeleInfo.getType() == 1) {//如果对方是用户，自己是主播
                        //自己是付费方，跳到付费页面
                        voiceEndData(intent);
                    } else {
                        removeActivity();
                    }
                }
            } else {
                removeActivity();
            }
        }

    }

    /**
     * @return
     * @method
     * @description 跳转评分页面
     * @date: 2018/12/13 19:34
     * @author: ljp
     */
    private void voiceEndData(Intent intent) {
        //intent.putExtra("mySelfInfoBean", mySelfInfoBean.getObject());
        intent.putExtra("voiceId", voiceId);
        startActivity(intent);
        removeActivity();
      /*  handle.postDelayed(new Runnable() {
            @Override
            public void run() {*/
                /*MeInfoService.voiceEndData(token, deviceInfo, mySeleInfo.getId(), voiceId).subscribe(mySelfInfoBean -> {
                    //Log.i(TAG, "voiceEndData: ---getCode-----"+mySelfInfoBean.getCode());
                    if (mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        intent.putExtra("mySelfInfoBean", mySelfInfoBean.getObject());
                        intent.putExtra("voiceId", voiceId);
                        startActivity(intent);
                    } else {
                    }
                }, throwable -> {
                    toast_MakeText(getResources().getString(R.string.net_error));
                    Log.i(TAG, "voiceEndData: -------" + throwable.toString());
                });
                removeActivity();*/
         //   }
       // },1000);

    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        if (isConner) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    startVideoService();
                }
            }
        }
        // Log.i(TAG, "onUserLeaveHint: --------------------");
    }
    //拨打电话期间不能返回
    @Override
    public void onBackPressed() {
    }

}
